package com.scuec.tourismwebsite.controller;

import com.scuec.tourismwebsite.entity.TouristAttraction;
import com.scuec.tourismwebsite.service.TouristAttractionService;
import com.github.pagehelper.PageInfo;
import com.scuec.tourismwebsite.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/tour/v1/attractions")
public class TouristAttractionController {
    @Autowired
    private TouristAttractionService touristAttractionService;

    @GetMapping
    public List<TouristAttraction> getAllAttractions() {
        return touristAttractionService.findAll();
    }

    @GetMapping("/{attraction_id}")
    public ResponseEntity<TouristAttraction> getAttractionById(@PathVariable Integer attraction_id) {
        return touristAttractionService.findById(attraction_id);
    }

    @PostMapping
    public ResponseEntity<TouristAttraction> addAttraction(@RequestBody TouristAttraction attraction) {
        return touristAttractionService.add(attraction);
    }

    @PutMapping("/{attraction_id}")
    public ResponseEntity<TouristAttraction> updateBasicInfo(@PathVariable Integer attraction_id, @RequestBody TouristAttraction attraction) {
        if (attraction_id != attraction.getAttraction_id()) {
            return ResponseEntity.badRequest().body(null);
        }
        // 这里可以添加更新基本信息的逻辑
        return touristAttractionService.updateBasicInfo(attraction_id, attraction);
    }

    @PutMapping("/detail")
    public ResponseEntity<TouristAttraction> updateDetail(@RequestBody TouristAttraction attraction) {
        Integer attractionId = attraction.getAttraction_id();
        if (attractionId == null) {
            return ResponseEntity.badRequest().build();  // 如果没有 ID，直接返回错误
        }

        ResponseEntity<TouristAttraction> update = touristAttractionService.update(attractionId, attraction);
        TouristAttraction updatedAttraction = update.getBody();

        if (updatedAttraction == null) {
            return ResponseEntity.notFound().build(); // 如果更新失败，返回 404
        }

        // 返回更新后的景点数据，确保包含所有需要的字段
        return ResponseEntity.ok(updatedAttraction);
    }



    @DeleteMapping("/{attraction_id}")
    public ResponseEntity<Void> deleteAttraction(@PathVariable Integer attraction_id) {
        return touristAttractionService.delete(attraction_id);
    }

    @GetMapping("/pages")
    public PageInfo<TouristAttraction> findAttractionsPages(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        return touristAttractionService.findAttractionsPages(pageNum, pageSize);
    }

    @GetMapping("/search")
    public ResponseEntity<PageInfo<TouristAttraction>> searchAttractions(@RequestParam String query, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<TouristAttraction> pageInfo = touristAttractionService.searchAttractions(query, pageNum, pageSize);
        return ResponseEntity.ok(pageInfo);
    }


    @GetMapping("/detail/{attraction_id}")
    public ResponseEntity<TouristAttraction> getAttractionDetail(@PathVariable("attraction_id") Integer attraction_id) {
        TouristAttraction attraction = touristAttractionService.getAttractionDetailById(attraction_id);
        if (attraction != null) {
            String photoFileName = attraction.getPhotos();
            if (photoFileName != null && !photoFileName.isEmpty()) {
                attraction.setPhotos("http://localhost:8080/images/upload/attractions/" + attraction.getPhotos());
            }
            return ResponseEntity.ok(attraction);
        } else {
            return ResponseEntity.notFound().build();
        }
    }



    //图片上传操作
    @PostMapping("upload")  // 图片上传
    public String getPicFileName(MultipartFile file, @RequestParam(required = false) Integer id) {
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);
        String typeName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String filePath = FileUtil.getUploadFilePath() + "/attractions";
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String newFileName = System.currentTimeMillis() + typeName;
        String photos = newFileName;
        System.out.println(newFileName);
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (id != null) {
            touristAttractionService.updatePhoto(id, photos);  // 仅在编辑时更新照片
        }

        return newFileName;  // 返回新上传的文件名
    }



}
